package com.campus_information_portal.service.impl; /**
 * @Description 宿舍管理实现类
 * @author 20155870 杨润增
 * @create 2018-04-24 20:11
 **/

import com.campus_information_portal.dao.DormitoryDao;
import com.campus_information_portal.dao.StudentDao;
import com.campus_information_portal.dao.TermDao;
import com.campus_information_portal.entity.DorStuTerm;
import com.campus_information_portal.entity.DormitoryApplyForm;
import com.campus_information_portal.service.DormitoryService;
import com.campus_information_portal.util.DateUtil;
import com.campus_information_portal.util.Message;
import com.campus_information_portal.util.Msg;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 20155870 杨润增
 * @className DomitoryImpl
 * @Description 宿舍管理实现类
 * @create 2018-04-24 20:11
 **/
@Service
public class DormitoryImpl implements DormitoryService {
    @Autowired
    private DormitoryDao dormitoryDao;
    @Autowired
    private StudentDao studentDao;
    @Autowired
    private TermDao termDao;

    @Override
    public List<DormitoryApplyForm> queryAllDormitoryApplyForm() {
        List<DormitoryApplyForm> dormitoryApplyFormList = new ArrayList<DormitoryApplyForm>();
        dormitoryApplyFormList = dormitoryDao.queryAllDormitoryApplyForm();
        return dormitoryApplyFormList;
    }

    @Override
    public List<DorStuTerm> queryAllDormitoryApplyForm_2() {
        List<DorStuTerm> list = dormitoryDao.queryAllDormitoryApplyForm_2();
        return list;
    }

    @Override
    public DormitoryApplyForm queryDormitoryApplyFormById(int dormitory_apply_form_id) {
        DormitoryApplyForm dormitoryApplyForm = new DormitoryApplyForm();
        dormitoryApplyForm = dormitoryDao.queryDormitoryApplyFormById(dormitory_apply_form_id);
        return dormitoryApplyForm;
    }

    @Override
    public DormitoryApplyForm queryDormitoryApplyFormByTermId(int term_id) {
        DormitoryApplyForm dormitoryApplyForm = new DormitoryApplyForm();
        dormitoryApplyForm = dormitoryDao.queryDormitoryApplyFormByTermId(term_id);
        return dormitoryApplyForm;
    }

    @Override
    public Msg queryDormitoryApplyFormByStu_info_id(int stu_info_id) {
       /* DormitoryApplyForm dormitoryApplyForm =  dormitoryDao.queryDormitoryApplyFormByStu_info_id(stu_info_id);
        if (dormitoryApplyForm!=null){
            return Msg.addData(100,)
        }
        return dormitoryApplyForm;*/
       return Msg.fail();
    }


    @Override
    public Msg addApply(int term_id, int stu_info_id, int dormitory_id, Date apply_date, String apply_reason, Date start_date, Date end_date, int apply_state) {
        int state = dormitoryDao.addApply(term_id, stu_info_id, dormitory_id, apply_date, apply_reason, start_date, end_date, apply_state);
        if (state==1){
            return Msg.addData(100,"成功",state);
        }
        return Msg.fail();
    }

    @Override
    public Msg addApply_2(DormitoryApplyForm dormitoryApplyForm) {
        int state = dormitoryDao.addApply_2(dormitoryApplyForm);
        if (state==1){
            return Msg.addData(100,"成功",state);
        }
        return Msg.fail();
    }

    @Override
    public Message addApply_3(Integer sutNum, String termYear, String termNum, Date startDate, Date endDate, String reason) {
        //首先根据sutNum查出stuInfoId
        int stuInfoId=studentDao.queryStudentByStuNum(sutNum).getStuInfoId();
        //根据学年以及学期查出termId
        int termId=termDao.queryTermId(termYear,termNum).getTermId();
        //根据stuInfoId查dormitoryNum
        int dormitoryNum=dormitoryDao.queryDormitoryNumByStuInfoId(stuInfoId).getDormitoryNum();
        if (endDate.before(startDate)){
            return Message.fail().add("申请失败,请检查申请时间","0901");
        }else {
            DormitoryApplyForm dormitoryApplyForm=new DormitoryApplyForm();
            dormitoryApplyForm.setTermId(termId);
            dormitoryApplyForm.setStuInfoId(stuInfoId);
            dormitoryApplyForm.setDormitoryNum(dormitoryNum);
            dormitoryApplyForm.setApplyDate(new Date());
            dormitoryApplyForm.setStartDate(startDate);
            dormitoryApplyForm.setEndDate(endDate);
            dormitoryApplyForm.setApplyReason(reason);
            /**
            *   0：未通过  1：通过  2：审核中
            **/
            dormitoryApplyForm.setApplyState(2);
            int flag=dormitoryDao.addApply_2(dormitoryApplyForm);
            if(flag==1){
                return Message.success();
            }
        }

        return Message.fail().add("申请失败","0901");

    }

    @Override
    public List<DormitoryApplyForm> query(DormitoryApplyForm dormitoryApplyForm) {
        List<DormitoryApplyForm> list = dormitoryDao.query(dormitoryApplyForm);
        return list;
    }

    @Override
    public Msg queryApplyByConditions(DorStuTerm dorStuTerm) {
        List<DorStuTerm> list = dormitoryDao.queryApplyByConditions(dorStuTerm);
        if (list.size() != 0) {
            return Msg.addData(100,"成功",list);
        }
        return Msg.fail();
    }

    public Message queryApplyByConditions_2(DorStuTerm dorStuTerm) {
        List<DorStuTerm> dorStuTermList = dormitoryDao.queryApplyByConditions(dorStuTerm);
        if (dorStuTermList.size() > 0) {
            return Message.success().add("dorStuTermList",dorStuTermList);
        }
        return Message.fail().add("0901","查询失败");
    }

    @Override
    public Message agreeApply(int dormitoryApplyFormId) {
        int flag = dormitoryDao.agreeApply(dormitoryApplyFormId);
        if(flag==1){
            return Message.success();
        }
        return Message.fail().add("0903","操作失败");
    }

    @Override
    public Message refuseApply(int dormitoryApplyFormId) {
        int flag = dormitoryDao.refuseApply(dormitoryApplyFormId);
        if(flag==1){
            return Message.success();
        }
        return Message.fail().add("0904","操作失败");
    }

    @Override
    public Msg queryDormitoryNumByStuInfoId(int stuInfoId) {
        /**
         * @Description 根据stu_info_id查询dormitory_num
         * @author 20155870 杨润增
         * @methodName queryDormitoryNumByStuInfoId
         * @param [stuInfoId]
         * @returnType com.campus_information_portal.util.Msg
         * @create 2018/5/18 16:31
         **/
        DormitoryApplyForm dormitoryApplyForm=dormitoryDao.queryDormitoryNumByStuInfoId(stuInfoId);
        if (dormitoryApplyForm!=null){
            System.out.println(dormitoryApplyForm.toString());
            return Msg.addData(100,"成功",dormitoryApplyForm);
        }
        return Msg.fail();
    }

    public Message download(String stuName,String stuSex,int dormitoryNum,String startDate,String endDate) throws UnknownHostException {
        // 模板路径.最终放在服务器下。远程即可访问
        String templatePath = "F:/专业设计/zsk.pdf";
        // 生成的新文件路径
        //首先获取获取本机计算机名称
        InetAddress addr = InetAddress.getLocalHost();
        String hostName=addr.getHostName().toString();
        //保存在桌面上
        String newPDFPath = "C:/Users/"+hostName+"/Desktop/留宿证.pdf";
        //这里应该访问远程的照片，数据表应加一列图片
        String imagePath = "F:/专业设计/ceng.png";

        //图片域的名字
        String fieldName = "img";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;

        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            int pageNo = form.getFieldPositions(fieldName).get(0).page;
            Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
            float x = signRect.getLeft();
            float y = signRect.getBottom();
            // 读图片
            Image image = Image.getInstance(imagePath);
            // 获取操作的页面
            PdfContentByte under = stamper.getOverContent(pageNo);
            // 根据域的大小缩放图片
            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
            // 添加图片
            image.setAbsolutePosition(x, y);
            under.addImage(image);
            //设置表单域的内容
            form.setField("stuName",stuName);
            form.setField("stuSex",stuSex);
            form.setField("dormitoryNum",String.valueOf(dormitoryNum));
            form.setField("startDate",startDate);
            form.setField("endDate",endDate);
            form.setField("issueDate", DateUtil.toString(new Date(),"yyyy-MM-dd"));
            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
            reader.close();

        } catch (IOException e) {
            System.out.println(1);
        } catch (DocumentException e) {
            System.out.println(2);
        }
        return Message.success();
    }


}
